function latextbl(TBL,fname,colformat,nanval)

if nargin<=3
    nanval = ' ';
end

if istable(TBL)
    TBL = table2cell(TBL);
end

if numel(colformat)==1
    colformat = repmat(colformat,[1 size(TBL,2)]);
end

for r = 1:size(TBL,1)
    for c = 1:size(TBL,2)
        if isnumeric(TBL{r,c})
            TBL{r,c} = num2str(TBL{r,c},colformat{c});
        end
    end
end

TBL = replace(TBL,'NaN',nanval);

TBLrows = arrayfun(@(r) [strjoin(TBL(r,:) ,' & ') '\\'],(1:size(TBL,1))','unif',0);
    
fid=fopen(fname,'w');
fwrite(fid,sprintf('%s \n',TBLrows {:}));
fclose(fid);

end